package com.itheima.jobs;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisConstant;
import com.itheima.utils.QiNiuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.Set;

/**
 * 自定义Job，实现定时清理垃圾图片
 */
@Component
public class ClearImgJob {

    /*@Autowired
    private JedisPool jedisPool;*/
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    @Scheduled(cron = "0/30 * * * * ?")
    public void clearImg(){
        System.out.println("定时任务开启"+new Date());
        //根据Redis中保存的两个set集合进行差值计算，获得垃圾图片名称集合
        //使用Jedis进行集合的减法
        //Set<String> set = jedisPool.getResource().sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SEMEAL_PIC_DB_RESOURCES);
        //使用RedisTemplate进行集合的减法
        Set<String> set = redisTemplate.opsForSet().difference(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SEMEAL_PIC_DB_RESOURCES);
        //System.out.println(set);
        if(set != null){
            for (String sName : set) {
                    //删除七牛云服务器上的图片
                    QiNiuUtils.deleteFileFromQiniu(sName);
                    //使用Jedis删除Redis数据库中的数据
                    //jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,sName);
                    //使用RedisTemplate删除Redis数据库中的数据
                    redisTemplate.boundSetOps(RedisConstant.SETMEAL_PIC_RESOURCES).remove(sName);
                    System.out.println("自定义任务执行，清理垃圾图片："+sName);
            }
        }

    }
}
